var rewardsM = require('../models/rewards.js');
var async = require('async');
var _VIEW_PATH = '../app_module/hongbao/views/';

module.exports = {
    giveCoupons:function(req,res,next){
        var uid = req.AV.user.id;
        var couponsId = req.params.couponsId ;
        var validityPeriod = req.params.validityPeriod ;
        console.log(uid)
        async.waterfall([
            function(callback){
                rewardsM.countCouponsFlow(uid, couponsId).then(function(data){
                    if(data.code === 0){
                        if(data.count >= 1){
                            //已达上限，不能发放
                            return callback(null, {code:-1,msg:'您已领取过优惠券'})
                        }else{
                            callback(null, {code:0});
                        }
                    }else{
                        callback({code:-2,msg:'网络故障，请重试'});
                    }
                }).catch(function(err){
                    callback({code:-2,msg:'网络故障，请重试'});
                });
            },
            function(count,callback){
                if(count.code === 0){
                    //允许发放奖品
                    rewardsM.giveCoupons(uid,couponsId,validityPeriod).then(function(data){
                        if(data.code === 0){
                            callback(null, {code:0,msg:'发放成功'})
                        }else{
                            callback(null, {code:-1,msg:'优惠券未设置'})
                        }
                    }).catch(function(err){
                        callback({code:-2,msg:'网络故障，请重试'});
                    });
                }else{
                    callback(null, {code:-1,msg:'您已领取过优惠券'})
                }
            },
            function(give,callback){
                if(give.code === 0){
                    rewardsM.couponsFlow(uid,couponsId).then(function(data){
                        if(data.code === 0){
                            //添加流水成功
                            callback(null, {code:0,msg:'发放成功'});
                        }else{
                            //添加流水失败
                            callback(null, {code:-1,msg:'添加流水失败'});
                        }
                    }).catch(function(err){
                        callback({code:-2,msg:'网络故障，请重试'});
                    });
                }else{
                    callback(null, {code:-1,msg:give.msg});
                }
            }

        ],function(err,results){
            if(err){
                res.json(err);
            }else{
                if(results.code === 0){
                    res.render(_VIEW_PATH+'huodong/giveCoupons_success',{msg:results.msg});
                }else{
                    res.render(_VIEW_PATH+'huodong/giveCoupons',{msg:results.msg});
                }

            }
        })
    }
};